// 预加载脚本：在渲染层安全地暴露必要 API，并注入平台信息到页面
const { contextBridge, ipcRenderer } = require('electron');
// 尝试加载 Node 内置 os 模块；在沙箱或受限环境下可能不可用
let os;
try {
    // 优先使用 node:os 前缀（新版本 Node 的推荐形式）
    // eslint-disable-next-line node/no-missing-require
    os = require('node:os');
} catch (_) {
    try {
        // 退回传统形式
        // eslint-disable-next-line node/no-missing-require
        os = require('os');
    } catch (e) {
        // 最终兜底：提供只读的占位实现，避免预加载脚本崩溃
        console.warn('[preload] os module unavailable, falling back to stubs:', e);
        os = {
            platform: () => 'Unavailable',
            arch: () => process.arch || 'Unavailable',
            release: () => 'Unavailable',
            type: () => 'Unavailable',
            hostname: () => 'Unavailable',
            totalmem: () => 0,
            freemem: () => 0,
            loadavg: () => [],
            cpus: () => []
        };
    }
}

// 统计：内存/CPU/磁盘
function getDiskStats() {
    try {
        const platform = process.platform;
        // 仅在 *nix/macOS 使用 df；Windows 返回 Unknown（可后续扩展 powershell）
        if (platform === 'win32') {
            return { total: 0, used: 0, free: 0, percent: 'Unknown' };
        }
        const { execSync } = require('child_process');
        const out = execSync('df -kP /').toString();
        const lines = out.trim().split(/\n/);
        const line = lines[lines.length - 1];
        const parts = line.trim().split(/\s+/);
        // 兼容列：1024-blocks Used Available Capacity Mounted on
        const totalKB = parseInt(parts[1], 10);
        const usedKB = parseInt(parts[2], 10);
        const availKB = parseInt(parts[3], 10);
        const capacity = parts[4];
        return {
            total: Number.isFinite(totalKB) ? totalKB * 1024 : 0,
            used: Number.isFinite(usedKB) ? usedKB * 1024 : 0,
            free: Number.isFinite(availKB) ? availKB * 1024 : 0,
            percent: capacity || 'Unknown'
        };
    } catch (e) {
        console.warn('[preload] getDiskStats failed:', e);
        return { total: 0, used: 0, free: 0, percent: 'Unknown' };
    }
}

function getSystemStats() {
    const totalMem = os.totalmem();
    const freeMem = os.freemem();
    const usedMem = (totalMem && freeMem) ? (totalMem - freeMem) : 0;
    const cpus = os.cpus();
    const cpuCount = Array.isArray(cpus) ? cpus.length : 0;
    const cpuModel = Array.isArray(cpus) && cpus[0] ? cpus[0].model : 'Unknown';
    const loadavg = os.loadavg();
    const disk = getDiskStats();
    return {
        memory: { total: totalMem, free: freeMem, used: usedMem },
        cpu: { count: cpuCount, model: cpuModel },
        loadavg: Array.isArray(loadavg) ? loadavg : [],
        disk
    };
}

// —— 五种系统检测方法 ——
// 方法一：process.platform（映射为友好名称并带架构）
function getOSMethod1() {
    const platform = process.platform;
    const arch = process.arch;
    const osMap = {
        darwin: 'macOS',
        win32: 'Windows',
        linux: 'Linux',
        freebsd: 'FreeBSD',
        openbsd: 'OpenBSD',
        sunos: 'SunOS',
        aix: 'AIX'
    };
    const osName = osMap[platform] || platform;
    return `${osName} (${arch})`;
}

// 方法二：os.platform()（附版本与架构）
function getOSMethod2() {
    const platform = os.platform();
    const arch = os.arch();
    const release = os.release();
    const osMap = {
        darwin: 'macOS',
        win32: 'Windows',
        linux: 'Linux',
        freebsd: 'FreeBSD',
        openbsd: 'OpenBSD',
        sunos: 'SunOS',
        aix: 'AIX'
    };
    const osName = osMap[platform] || platform;
    return `${osName} ${release} (${arch})`;
}

// 方法三：os.type()（更接近系统原始名称）
function getOSMethod3() {
    const type = os.type();
    const arch = os.arch();
    const release = os.release();
    const hostname = os.hostname();
    return `${type} ${release} (${arch}) @ ${hostname}`;
}

// 方法四：navigator.platform（Web 标准 API）
function getOSMethod4() {
    try {
        const platform = navigator.platform || '';
        let osName = 'Unknown';
        if (platform.includes('Mac')) osName = 'macOS (via Navigator)';
        else if (platform.includes('Win')) osName = 'Windows (via Navigator)';
        else if (platform.includes('Linux')) osName = 'Linux (via Navigator)';
        else if (platform.includes('iPhone') || platform.includes('iPad')) osName = 'iOS (via Navigator)';
        return `${osName} - ${platform}`;
    } catch (e) {
        return 'Unknown';
    }
}

// 方法五：navigator.userAgent（传统 UA 解析）
function getOSMethod5() {
    try {
        const ua = navigator.userAgent || '';
        // macOS
        if (ua.includes('Mac OS X')) {
            const match = ua.match(/Mac OS X (\d+[._]\d+[._]\d+)/);
            if (match) {
                const version = match[1].replace(/_/g, '.');
                return `macOS ${version}`;
            }
            return 'macOS (version unknown)';
        }
        // Windows
        if (ua.includes('Windows NT')) {
            const match = ua.match(/Windows NT (\d+\.\d+)/);
            if (match) {
                const versionMap = {
                    '10.0': 'Windows 10/11',
                    '6.3': 'Windows 8.1',
                    '6.2': 'Windows 8',
                    '6.1': 'Windows 7',
                    '6.0': 'Windows Vista',
                    '5.1': 'Windows XP'
                };
                return versionMap[match[1]] || `Windows NT ${match[1]}`;
            }
            return 'Windows (version unknown)';
        }
        // Linux / Android
        if (/Android/i.test(ua)) return 'Android';
        if (/Linux/i.test(ua)) return 'Linux';
        // iOS
        if (/iPhone|iPad|iPod/i.test(ua)) return 'iOS';
        return 'Unknown';
    } catch (e) {
        return 'Unknown';
    }
}

// 暴露安全的 API 给渲染进程
// 重构：以函数形式提供平台信息，避免时序问题导致页面读取为“未知”
contextBridge.exposeInMainWorld('electronAPI', {
    // 获取早报数据（保留示例）
    fetchZaobao: () => ipcRenderer.invoke('fetch-zaobao'),

    // 获取版本信息
    versions: {
        chrome: process.versions.chrome,
        node: process.versions.node,
        electron: process.versions.electron
    },

    // 同步函数返回平台信息对象（含五种检测方式与原始字段）
    getPlatformInfo: () => ({
        method1: getOSMethod1(),
        method2: getOSMethod2(),
        method3: getOSMethod3(),
        method4: getOSMethod4(),
        method5: getOSMethod5(),
        stats: getSystemStats(),
        // 兼容旧字段（如果页面仍使用 p-way1/2/3）
        way1: os.type(),
        way2: process.platform,
        way3: (typeof navigator !== 'undefined' ? navigator.userAgent : ''),
        raw: {
            processPlatform: process.platform,
            processArch: process.arch,
            osPlatform: os.platform(),
            osArch: os.arch(),
            osRelease: os.release(),
            hostname: os.hostname(),
            navigatorPlatform: (typeof navigator !== 'undefined' ? navigator.platform : ''),
            userAgent: (typeof navigator !== 'undefined' ? navigator.userAgent : '')
        }
    }),

    // 异步兜底：通过主进程获取平台信息（避免预加载受限时失败）
    fetchPlatformInfo: () => ipcRenderer.invoke('get-platform-info')
});

// 将平台信息以浮层形式展示在页面左下角
// 说明：由于主窗口当前加载的是远程页面（Electron 文档站），我们通过 preload 在隔离上下文中
// 操作 DOM 注入一个安全的提示框，不修改站点原有脚本，兼容 CSP。
function injectPlatformBanner() {
    const info = {
        processPlatform: process.platform,
        osPlatform: os.platform(),
        osType: os.type()
    };

    const banner = document.createElement('div');
    banner.id = 'platform-info-banner';
    banner.setAttribute('role', 'status');
    banner.setAttribute('aria-live', 'polite');
    banner.style.position = 'fixed';
    banner.style.left = '12px';
    banner.style.bottom = '12px';
    banner.style.zIndex = '2147483647';
    banner.style.background = 'rgba(0,0,0,0.65)';
    banner.style.color = '#fff';
    banner.style.fontFamily = 'system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
    banner.style.fontSize = '12px';
    banner.style.lineHeight = '1.5';
    banner.style.padding = '10px 12px';
    banner.style.borderRadius = '8px';
    banner.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
    banner.style.backdropFilter = 'blur(4px)';

    banner.innerHTML = [
        '<strong>系统平台信息</strong>',
        `运行平台（process.platform）：<code>${info.processPlatform}</code>`,
        `操作系统平台（os.platform()）：<code>${info.osPlatform}</code>`,
        `操作系统类型（os.type()）：<code>${info.osType}</code>`
    ].join('<br/>');

    // 防止重复注入
    if (!document.getElementById('platform-info-banner')) {
        document.body.appendChild(banner);
    }
}

// 等待文档就绪再注入，避免页面未加载完成无法插入
window.addEventListener('DOMContentLoaded', () => {
    try {
        // 优先填充本地页面占位元素（若存在），否则注入远程页面浮层
        const placeholders = ['p-m1','p-m2','p-m3','p-m4','p-m5','p-process','p-os-platform','p-way1','p-way2','p-way3',
            'p-mem-total','p-mem-free','p-mem-used','p-cpu-count','p-cpu-model','p-load-avg','p-disk-total','p-disk-used','p-disk-free','p-disk-pct'];
        const hasPlaceholders = placeholders.some(id => document.getElementById(id));

        const info = {
            method1: getOSMethod1(),
            method2: getOSMethod2(),
            method3: getOSMethod3(),
            method4: getOSMethod4(),
            method5: getOSMethod5(),
            stats: getSystemStats(),
            raw: {
                processPlatform: process.platform,
                osPlatform: os.platform()
            }
        };

        const setText = (id, value) => {
            const el = document.getElementById(id);
            if (el) el.textContent = value ?? '未知';
        };

        console.log('[preload] DOMContentLoaded. hasPlaceholders=', hasPlaceholders, 'info=', info);
        if (hasPlaceholders) {
            // 新版页面占位
            setText('p-m1', info.method1);
            setText('p-m2', info.method2);
            setText('p-m3', info.method3);
            setText('p-m4', info.method4);
            setText('p-m5', info.method5);
            // 兼容旧版占位
            setText('p-way1', info.method1);
            setText('p-way2', info.method2);
            setText('p-way3', info.method3);
            setText('p-process', info.raw.processPlatform);
            setText('p-os-platform', info.raw.osPlatform);

            // 统计数据
            const s = info.stats;
            setText('p-mem-total', s?.memory?.total);
            setText('p-mem-free', s?.memory?.free);
            setText('p-mem-used', s?.memory?.used);
            setText('p-cpu-count', s?.cpu?.count);
            setText('p-cpu-model', s?.cpu?.model);
            setText('p-load-avg', Array.isArray(s?.loadavg) ? s.loadavg.join(', ') : '');
            setText('p-disk-total', s?.disk?.total);
            setText('p-disk-used', s?.disk?.used);
            setText('p-disk-free', s?.disk?.free);
            setText('p-disk-pct', s?.disk?.percent);
        } else {
            injectPlatformBanner();
        }
    } catch (e) {
        console.error('[preload] 注入平台信息失败:', e);
    }
});